<script setup>
import fieldModel from "@/models/fieldModel.js"
import com from "@/utils/common.js"

import { computed, defineProps, ref } from "vue";

const { meta, vm } = defineProps(["meta", "vm"]);
const enumEntry = meta["enum-values"] || [];
const dataModel = vm.getModelRef(meta.model);
const field = fieldModel(vm, dataModel, meta);

const v = ref({});

const enumItems = [];
enumEntry.forEach(x => {
  enumItems.push(enumItemModel(x));
});

const enumModelRef = ref(enumItems);


const fieldValue = field.value.getValue();
if (fieldValue) {
  fieldValue.split(',').forEach(x => {
    v.value[x] = true;
  });
}

function enumItemModel(desc) {
  const { name, title, value } = desc;
  const m = {
    name,
    title,
    value,
    _checked: false,
    checked: computed({
      get() {
        return v.value[value];
      },
      set(newValue) {
        v.value[value] = newValue;
        handleValueChange();
      }
    })
  };
  return m;
}


function handleValueChange() {
  let checkItems = enumModelRef.value.filter(x => {
    return v.value[x.value];
  });
  field.value.setValue(com.utils.join(checkItems, ",", x => x.value));
  v.value["_DisplayValue__"] = com.utils.join(checkItems, ",", x => x.title);
}


const displayValue = computed(() => {
  return v.value["_DisplayValue__"];
});

handleValueChange();
</script>

<template>
  <span v-if="field.isEditing">
    <el-checkbox v-for="item in enumModelRef" v-model="item.checked" :label="item.title" />
  </span>
  <el-text v-else>{{ displayValue }}</el-text>
</template>